//
//  MHMomentHelper.m
//  MHDevelopExample
//
//Created by acgera on 2018/4/9.
//  Copyright © 2018年 acgera. All rights reserved.
//  

#import "MHMomentHelper.h"
#import "MHMomentVideo.h"
#import "MHInitalLocationModel.h"
#import "MHFuQian.h"
//#import "MHMomentOperationMoreView.h"

@implementation MHMomentHelper
+ (NSDateFormatter *)dateFormatter{
    static NSDateFormatter *fmt = nil;
    /// 由于NSDateFormatter 有一定的性能问题 故全局共享一个
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
        ///  真机调试的时候，必须加上这句
        fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    });
    return fmt;
}





+(void) shareWithSharRecent:(MHshareRecent *) shareRecent shareType:(MHCirclShareType) shareType
{
    OSMessage *msg=[[OSMessage alloc] init];
    msg.title=shareRecent.title;
    msg.link = shareRecent.webUrl;
    msg.desc = shareRecent.intro;
    UIImage *img;
    if ([shareRecent.coverUrl hasPrefix:@"http"]) {
        NSURL *url = [NSURL URLWithString:shareRecent.coverUrl];
        NSData *data = [NSData dataWithContentsOfURL:url];
       img = [[UIImage alloc] initWithData:data];
    }else
    {
        img = MHImageNamed(shareRecent.coverUrl);
    }

    UIImage *thumbImage;
    if (img) {
        thumbImage = img;
    }else
    {
        thumbImage = [UIImage imageNamed:@"AppIcon"];
    }
    NSData *compressData = [thumbImage compressWithLengthLimit:31 *1024];
    msg.image = compressData;
    
    if (shareType == MHCirclShareTypeWeChat) {
        [[[MHHTTPService sharedInstance] updateRecentShareCountWithRecentId:shareRecent.targetId type:MHCirclShareTypeWeChat] subscribeNext:^(id x) {
            
        }];
        [OpenShare shareToWeixinSession:msg Success:^(OSMessage *message) {
            
        } Fail:^(OSMessage *message, NSError *error) {
            
        }];
    }else
    {
        [[[MHHTTPService sharedInstance] updateRecentShareCountWithRecentId:shareRecent.targetId type:MHCirclShareTypeWeChatTimeLine] subscribeNext:^(id x) {
            
        }];
        [OpenShare shareToWeixinTimeline:msg Success:^(OSMessage *message) {
            
            
        } Fail:^(OSMessage *message, NSError *error) {
            
        }];
    }
    
//    [weakSelf.zh_popupController dismiss];
}




/// 时间转化
+ (NSString *) createdAtTimeWithSourceDate:(NSDate *)sourceDate{
    if (MHObjectIsNil(sourceDate)) return @"";
    // 判断是否为今年
    if (sourceDate.mh_isThisYear) {
        if (sourceDate.mh_isToday) { // 今天
            NSDateComponents *cmps = [sourceDate mh_deltaWithNow];
            if (cmps.hour >= 1) { // 至少是1小时前发的
                return [NSString stringWithFormat:@"%zd小时前", cmps.hour];
            } else if (cmps.minute >= 1) { // 1~59分钟之前发的
                return [NSString stringWithFormat:@"%zd分钟前", cmps.minute];
            }else { // 1分钟内发的
                return @"刚刚";
            }
        } else if (sourceDate.mh_isIntervalThreeDay) { // 昨天
            self.dateFormatter.dateFormat = @"yyyy-MM-dd";
            return [self.dateFormatter stringFromDate:sourceDate];
        } else if(sourceDate.mh_daysInterVal <= 3){ // 至少是前天
//            [self dateFormatter].dateFormat = ;
            return [NSString stringWithFormat:@"%d天前",sourceDate.mh_daysInterVal];
        }else
        {
            [self dateFormatter].dateFormat = @"MM-dd HH:mm";
            return [self.dateFormatter stringFromDate:sourceDate];
        }
    } else { // 非今年
        self.dateFormatter.dateFormat = @"yyyy-MM-dd";
        return [self.dateFormatter stringFromDate:sourceDate];
    }
}


+ (NSString *)gloabalDateTransfer:(NSDate *)sourceDate{
       if (MHObjectIsNil(sourceDate)) return @"";
        self.dateFormatter.dateFormat = @"yyyy-MM-dd";
        return [self.dateFormatter stringFromDate:sourceDate];

}


/// 电话号码正则
+ (NSRegularExpression *)regexPhoneNumber{
    static NSRegularExpression *regex;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        regex = [NSRegularExpression regularExpressionWithPattern:@"\\d{3,4}[- ]?\\d{7,8}" options:kNilOptions error:NULL];
    });
    return regex;
}

/// 链接正则
+ (NSRegularExpression *)regexLinkUrl{
    static NSRegularExpression *regex;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        regex = [NSRegularExpression regularExpressionWithPattern:@"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)" options:kNilOptions error:NULL];
    });
    return regex;
}


//-(void)openCameraIsPublish:(BOOL) isPublish selectedAssets:(NSArray *)selecatedAssets completionBlock:(VoidBlock_id_id)completionBlock  {
//    [MHPhotoManager fetchPhotosFromAlbum:self maxImagesCount:isPublish?9:1 allowCrop:NO selectedAssets:selecatedAssets completion:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto, NSArray<NSDictionary *> *infos) {
//        NSMutableArray *photesArray =  [MHPhotoManager selectedAlbumPhotosIncludingGifWithPHAssets:assets photos:photos];
//        completionBlock(photesArray,assets);
//    } cancel:^{
//
//    }];
//}


+ (void)hideAllPopViewWithAnimated:(BOOL)animated{
    /// 关闭键盘
    if(MHSharedAppDelegate.isShowKeyboard){ [[UIApplication sharedApplication].keyWindow endEditing:YES]; }
}


+(void) redirectToGroupChatWithCircleId:(int )circleId service:(id<MHViewModelServices>) service groupId:(NSString *) groupId title:(NSString *) title
{
    __block IMAUser *user =  [[IMAPlatform sharedInstance].contactMgr getUserByGroupId:groupId];
    if(!user)
    {
        
        [[TIMGroupManager sharedInstance] getGroupInfo:@[groupId] succ:^(NSArray *array) {
            
            if (array.count)
            {
                TIMGroupInfo *groupInfo = array[0];
                user = [[IMAGroup alloc] initWithInfo:groupInfo];
                [[IMAPlatform sharedInstance].contactMgr.groupList addObject:user];
                MHChatViewModel *viewModel = [[MHChatViewModel alloc] initWithServices:service params:@{MHViewModelUtilKey:user,MHViewModelIDKey:@(circleId)}];
                viewModel.title = title;
                [service pushViewModel:viewModel animated:YES];
                
            }
        } fail:^(int code, NSString *err) {
            
            [[TIMGroupManager sharedInstance] joinGroup:groupId msg:@"" succ:^(){
                    IMAGroup *user = [[IMAGroup alloc] initWith:groupId];
                    MHChatViewModel *viewModel = [[MHChatViewModel alloc] initWithServices:service params:@{MHViewModelUtilKey:user,MHViewModelIDKey:@(circleId)}];
                    viewModel.title = title;
                    [service pushViewModel:viewModel animated:YES];
            }fail:^(int code, NSString * err) {
                
                MLCircleInfoMainPageViewModel *viewModel = [[MLCircleInfoMainPageViewModel alloc] initWithServices:service params:@{MHViewModelIDKey:@(circleId)}];
                [service pushViewModel:viewModel animated:YES];
                
            }];
            
        }];
    }else
    {
        MHChatViewModel *viewModel = [[MHChatViewModel alloc] initWithServices:service params:@{MHViewModelUtilKey:user,MHViewModelIDKey:@(circleId)}];
        viewModel.title = title;
        [service pushViewModel:viewModel animated:YES];
    }
}

+(void) enterOrJionCircleWithViewModel:(MHViewModel *)viewModel joinSuccessBlock:(VoidBlock) successBlock;
{
    @weakify(self);
    if([AXAppDelegate sharedDelegate].currentDiscoverModel.isInCircle)
    {
        [self redirectToGroupChatWithCircleId:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleId service:viewModel.services groupId:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleCode title:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleName];
        
//        //                    MHCircleHomeModel *circle = self.circles[indexPath.row];
//        MLCircleInfoMainPageViewModel *infoViewModel = [[MLCircleInfoMainPageViewModel alloc] initWithServices:viewModel.services params:@{MHViewModelIDKey:@([AXAppDelegate sharedDelegate].currentDiscoverModel.circleId)}];
//        [viewModel.services pushViewModel:infoViewModel  animated:YES];
    }else
    {
        if ([AXAppDelegate sharedDelegate].currentDiscoverModel.payType == 2) {
            
            
            if([AXAppDelegate sharedDelegate].isAuthorizationExpired)
            {
                [[[MHHTTPService sharedInstance] appFuQinJoinCircleWithCircleId:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleId openid:@"" inviteUserKey:@""] subscribeNext:^(MHFuQian *fuqian) {
                    [OpenShare OpenUrlLink:fuqian.urlScheme Success:^(NSDictionary *message) {
                        
                    } Fail:^(NSDictionary *message, NSError *error) {
                        
                    }];
                }];
            }else
            {
                [[viewModel.fetchQrCodeLinkCommond  execute:nil] subscribeNext:^(MHQRCodeModel *qrCodeModel) {
                    OSMessage *msg=[[OSMessage alloc] init];
                    msg.title=qrCodeModel.title;
                    msg.link = qrCodeModel.webUrl;
                    msg.desc = qrCodeModel.intro;
                    NSURL *url = [NSURL URLWithString:qrCodeModel.coverUrl];
                    NSData *data = [NSData dataWithContentsOfURL:url];
                    UIImage *img = [[UIImage alloc] initWithData:data];
                    UIImage *thumbImage;
                    if (img) {
                        thumbImage = img;
                    }else
                    {
                        thumbImage = [UIImage imageNamed:@"AppIcon"];
                    }
                    NSData *compressData = [thumbImage compressWithLengthLimit:31 *1024];
                    msg.image = compressData;
                    [OpenShare shareToWeixinSession:msg Success:^(OSMessage *message) {
                        
                    } Fail:^(OSMessage *message, NSError *error) {
                    }];
                }];
            }
            
            
        }else
        {
            
            LCActionSheet *sheet = [LCActionSheet sheetWithTitle:[NSString stringWithFormat:@"确定加入%@",[AXAppDelegate sharedDelegate].currentDiscoverModel.circleName] cancelButtonTitle:@"取消" clicked:^(LCActionSheet * _Nonnull actionSheet, NSInteger buttonIndex) {
                if (buttonIndex == 0) return;
                @strongify(self);
                @weakify(self);
                [[viewModel.applyCommand execute:nil] subscribeNext:^(MHHTTPResponse *respose) {
                    @strongify(self);
                    [MBProgressHUD mh_showTips:@"加入成功"];
                    [AXAppDelegate sharedDelegate].currentDiscoverModel.isInCircle = true;
                    [MHNotificationCenter postNotificationName:MHReloadFirstPageDataNotification object:nil];
                    [MHNotificationCenter postNotificationName:MHReloadHomeDiscoverDataNotification object:nil];
                    
                    if(successBlock)
                    {
                        successBlock();
                    }
//                    MLCircleInfoMainPageViewModel *viewModel = [[MLCircleInfoMainPageViewModel alloc] initWithServices:viewModel.services params:@{MHViewModelIDKey:@([AXAppDelegate sharedDelegate].currentDiscoverModel.circleId)}];
//                    [viewModel.services pushViewModel:viewModel animated:YES];
                }];
            } otherButtonTitles:@"确定", nil];
            NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];
            [indexSet addIndex:1];
            sheet.destructiveButtonIndexSet = indexSet;
            [sheet show];
            
        }
    }
}



+(void) enterOrJionCircleWithViewModel:(MHViewModel *)viewModel
{
    @weakify(self);
        if([AXAppDelegate sharedDelegate].currentDiscoverModel.isInCircle)
        {
            //                    MHCircleHomeModel *circle = self.circles[indexPath.row];
            
             [self redirectToGroupChatWithCircleId:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleId service:viewModel.services groupId:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleCode title:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleName];
            
//            MLCircleInfoMainPageViewModel *infoViewModel = [[MLCircleInfoMainPageViewModel alloc] initWithServices:viewModel.services params:@{MHViewModelIDKey:@([AXAppDelegate sharedDelegate].currentDiscoverModel.circleId)}];
//            [viewModel.services pushViewModel:infoViewModel  animated:YES];
        }else
        {
            if ([AXAppDelegate sharedDelegate].currentDiscoverModel.payType == 2) {
                
                if([AXAppDelegate sharedDelegate].isAuthorizationExpired)
                {
                    [[[MHHTTPService sharedInstance] appFuQinJoinCircleWithCircleId:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleId openid:@"" inviteUserKey:@""] subscribeNext:^(MHFuQian *fuqian) {
                        [OpenShare OpenUrlLink:fuqian.urlScheme Success:^(NSDictionary *message) {
                            
                        } Fail:^(NSDictionary *message, NSError *error) {
                            
                        }];
                    }];
                }else
                {
                    [[viewModel.fetchQrCodeLinkCommond  execute:nil] subscribeNext:^(MHQRCodeModel *qrCodeModel) {
                        OSMessage *msg=[[OSMessage alloc] init];
                        msg.title=qrCodeModel.title;
                        msg.link = qrCodeModel.webUrl;
                        msg.desc = qrCodeModel.intro;
                        NSURL *url = [NSURL URLWithString:qrCodeModel.coverUrl];
                        NSData *data = [NSData dataWithContentsOfURL:url];
                        UIImage *img = [[UIImage alloc] initWithData:data];
                        UIImage *thumbImage;
                        if (img) {
                            thumbImage = img;
                        }else
                        {
                            thumbImage = [UIImage imageNamed:@"AppIcon"];
                        }
                        NSData *compressData = [thumbImage compressWithLengthLimit:31 *1024];
                        msg.image = compressData;
                        [OpenShare shareToWeixinSession:msg Success:^(OSMessage *message) {
                            
                        } Fail:^(OSMessage *message, NSError *error) {
                        }];
                    }];
                }
                
            }else
            {
                
                LCActionSheet *sheet = [LCActionSheet sheetWithTitle:[NSString stringWithFormat:@"确定加入%@",[AXAppDelegate sharedDelegate].currentDiscoverModel.circleName] cancelButtonTitle:@"取消" clicked:^(LCActionSheet * _Nonnull actionSheet, NSInteger buttonIndex) {
                    if (buttonIndex == 0) return;
                    @strongify(self);
                    @weakify(self);
                    [[viewModel.applyCommand execute:nil] subscribeNext:^(MHHTTPResponse *respose) {
                        @strongify(self);
                        [MBProgressHUD mh_showTips:@"加入成功"];
                        [AXAppDelegate sharedDelegate].currentDiscoverModel.isInCircle = true;
                        [MHNotificationCenter postNotificationName:MHReloadFirstPageDataNotification object:nil];
                        [MHNotificationCenter postNotificationName:MHReloadHomeDiscoverDataNotification object:nil];
                        [MHNotificationCenter postNotificationName:MHReloadDiscoverHomeCircleDataNotification object:nil];
//                        MLCircleInfoMainPageViewModel *viewModel = [[MLCircleInfoMainPageViewModel alloc] initWithServices:viewModel.services params:@{MHViewModelIDKey:@([AXAppDelegate sharedDelegate].currentDiscoverModel.circleId)}];
//                        [viewModel.services pushViewModel:viewModel animated:YES];
                        [self redirectToGroupChatWithCircleId:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleId service:viewModel.services groupId:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleCode title:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleName];
                    }];
                } otherButtonTitles:@"确定", nil];
                NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];
                [indexSet addIndex:1];
                sheet.destructiveButtonIndexSet = indexSet;
                [sheet show];
                
            }
        }
}



+ (void)createFilePath:(NSString *)path{
    NSFileManager *fileManager = [NSFileManager new];
    BOOL isDir = NO;
    if ([fileManager fileExistsAtPath:path isDirectory:&isDir]) {
        
    } else {
        [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
}

+ (NSString *)createWebpFilePathWith:(MHMomentVideo *)momentVideo{
    NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp/Media"];
    [self createFilePath:path];
    NSString *uuidStr = [[NSUUID UUID] UUIDString];
    NSString * fileName = [NSString stringWithFormat:@"%@.webp",momentVideo.videoId];
    return [path stringByAppendingPathComponent:fileName];
}


+ (NSString * )saveToWebpByVideoPath:(MHMomentVideo *)momentVideo{
    NSString * filePath = [self createWebpFilePathWith:momentVideo];
    YYImageEncoder *gifEncoder = [[YYImageEncoder alloc] initWithType:YYImageTypeWebP];
    gifEncoder.loopCount = 0;
    gifEncoder.quality = 0.8;
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:momentVideo.videoURL options:nil];
    int64_t value = asset.duration.value;
    int64_t scale = asset.duration.timescale;
    
    AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    generator.appliesPreferredTrackTransform = YES;
    //下面两个值设为0表示精确取帧，否则系统会有优化取出来的帧时间间隔不对等
    generator.requestedTimeToleranceAfter = kCMTimeZero;
    generator.requestedTimeToleranceBefore = kCMTimeZero;
    
    for (int i = 0; i <=4; i++) {
        CGFloat starttime = i*0.1+0.5;
        CMTime time = CMTimeMakeWithSeconds(starttime, (int)scale);
        NSError *error = nil;
        CMTime actualTime;
        CGImageRef image = [generator copyCGImageAtTime:time actualTime:&actualTime error:&error];
        UIImage * img = [UIImage imageWithCGImage:image];
        img = [self resizeToMaxHeight:480 img:img];
        [gifEncoder addImage:img duration:0.1];
        CGImageRelease(image);
    }
    for (int i=3; i>=0; i--) {
        CGFloat starttime = i*0.1+0.5;
        CMTime time = CMTimeMakeWithSeconds(starttime, (int)scale);
        NSError *error = nil;
        CMTime actualTime;
        CGImageRef image = [generator copyCGImageAtTime:time actualTime:&actualTime error:&error];
        UIImage * img = [UIImage imageWithCGImage:image];
        img = [self resizeToMaxHeight:480 img:img];
        [gifEncoder addImage:img duration:0.1];
        CGImageRelease(image);
    }
    
    [gifEncoder encodeToFile:filePath];
    NSLog(@"生成webp成功!");
    return filePath;
}

+ (UIImage *)resizeToMaxHeight:(CGFloat)height img:(UIImage *)img{
    if (img.size.width<img.size.height) {
        if (img.size.height>height) {
            CGSize newSize = CGSizeMake(height*1.0*img.size.width/img.size.height, height);
            img = [img yy_imageByResizeToSize:newSize contentMode:UIViewContentModeScaleToFill];
        }
    }
    else{
        if (img.size.width>height) {
            CGSize newSize = CGSizeMake(height,img.size.height*height*1.0/img.size.width);
            img = [img yy_imageByResizeToSize:newSize contentMode:UIViewContentModeScaleToFill];
        }
    }
    return img;
}
@end
